package com.efei.ehcache;

import com.alibaba.fastjson.JSONObject;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(System.getProperty("user.dir"));
        //Resource resource = new FileSystemResource("classpath:ehcache.xml");
        //System.out.println(Test1.class.getResource("/ehcache.xml"));
        // 1. 创建缓存管理器
        CacheManager cacheManager = CacheManager.create(Test1.class.getResource("classpath:ehcache.xml"));

        // 2. 获取缓存对象
        Cache cache = cacheManager.getCache("Cache2");
        for(int i=0;i<1;i++){
            // 3. 创建元素
            Element element = new Element("key"+i, "value"+i);
            // 4. 将元素添加到缓存
            cache.put(element);
        }


        while (cache.getSize()>0){
            Thread.sleep(1*1000);
            System.out.println("1s");
            //System.out.println(cache.get("key" + 0));
        }


        // 5. 获取缓存
        System.out.println(cache.get("key" + 0));
//        Element value = cache.get("key1");
//        System.out.println(value);
//        System.out.println(value.getObjectValue());



        // 6. 删除元素
//        cache.remove("key1");
//
//        JSONObject p1 = new JSONObject();
//        p1.put("小明","杭州");
//        Element pelement = new Element("xm",p1);
//        cache.put(pelement);
//        Element pelement2 = cache.get("xm");
//        System.out.println(pelement2.getObjectValue());

        System.out.println(cache.getSize());

        // 7. 刷新缓存
        cache.flush();

        // 8. 关闭缓存管理器
        cacheManager.shutdown();

    }
}
